package com.example.user.service.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.framework.common.constant.BaseHeaders;
import com.example.framework.common.exception.ServiceException;
import com.example.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.example.framework.common.util.json.JsonUtils;
import com.example.framework.security.core.LoginUser;
import com.example.framework.web.core.util.WebFrameworkUtils;
import com.example.user.constants.SourceTypeEnum;
import com.example.user.controller.auth.vo.UserSourceType;
import com.example.user.dal.dataobject.user.AdminUserDO;
import com.example.user.dal.mysql.user.AdminUserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Optional;

@Service
public class AdminUserService {

    @Resource
    private AdminUserMapper adminUserMapper;

    public static LambdaQueryWrapper<AdminUserDO> buildAdminUserQueryWrapper(UserSourceType reqVo) {
        Integer source = reqVo.getSource();
        if (SourceTypeEnum.NAME.getType() != source) {
            throw ServiceException.of(GlobalErrorCodeConstants.NOT_IMPLEMENTED);
        }
        return Wrappers.<AdminUserDO>lambdaQuery().eq(AdminUserDO::getName, reqVo.getId());
    }

    public LoginUser loadLoginUserByUserSourceType(UserSourceType userSourceType) {
        AdminUserDO adminUserDO = adminUserMapper.selectOne(buildAdminUserQueryWrapper(userSourceType));
        if (Objects.isNull(adminUserDO)) {
            throw ServiceException.of(GlobalErrorCodeConstants.USER_NOT_FOUND);
        }
        return new LoginUser()
                .setUsername(adminUserDO.getUserId())
                .setPassword(adminUserDO.getPassword())
                .setPermissions(JsonUtils.parseArray(adminUserDO.getPermissions(), String.class))
                .setNickname(adminUserDO.getName())
                .setDeviceId(Optional.ofNullable(WebFrameworkUtils.getRequest())
                        .map(request -> request.getHeader(BaseHeaders.X_DEVICE_ID))
                        .orElse("unknown"));
    }
}
